package cn.edu.sjtu.spinning.service.impl;

import cn.edu.sjtu.spinning.domain.Task;
import cn.edu.sjtu.spinning.dto.StateResponse;
import cn.edu.sjtu.spinning.dto.TaskInput;
import cn.edu.sjtu.spinning.enums.RespStatus;
import cn.edu.sjtu.spinning.exception.model.ServiceException;
import cn.edu.sjtu.spinning.service.SpinningService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

/**
 * @author loumoon
 * @date 2019-11-20 10:04
 */
@Service("WithDevice")
@Slf4j
public class SpinningServiceImpl implements SpinningService {

  private final RestTemplate restTemplate;

  @Value("${spinning.data.source.url}")
  private String dataSourceUrl; // 数据源的url

  @Value("${spinning.identifier}")
  private Integer spinningIdentifier; // 旋压工序的编号

  @Value("${spinning.instance}")
  private Integer spinningInstance; // 本旋压微服务实例的id

  private Queue<TaskInput> processes = new LinkedList<>(); // 微服务待处理的task队列
  private TaskInput task; // 当前在处理的task

  public SpinningServiceImpl(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
  }

  /*查询当前设备处理状态*/
  //    public JSONObject queryTaskState() {
  //        Map<String, Integer> requestParams = new HashMap<>();
  //        requestParams.put("num", spinningIdentifier);
  //        requestParams.put("instance", spinningInstance);
  //
  //        ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(dataSourceUrl +
  // "?args={args}", JSONObject.class, requestParams);
  //
  //        JSONObject responseBody = responseEntity.getBody();
  //        if (responseBody == null) {
  //            throw new ServiceException(RespStatus.INVALID_RESPONSE_FROM_OPC,
  // this.getClass().getName());
  //        }
  //        responseBody.put("processId", task.getProcessId());
  //        responseBody.put("taskId", task.getTaskId());
  //
  //        // 检查设备状态，判断是否可以处理新的task
  //        if ((int) responseBody.get("status") == DeviceStatus.READY.ordinal()) {
  //            task = processes.poll(); // 取出新的task并开始处理
  //            if (task != null) {
  //                if (!start(task).get("message").equals("execute success")) {
  //                    throw new ServiceException(RespStatus.FAIL_START_DEVICE,
  // this.getClass().getName());
  //                }
  //            }
  //        }
  //        return responseBody;
  //    }

  /*开始处理Task*/
  private JSONObject start(TaskInput task) {
    JSONObject requestBody = new JSONObject();
    requestBody.put("num", spinningIdentifier);
    requestBody.put("instance", spinningInstance);
    requestBody.put("data", task.getParams()); // 输入参数

    ResponseEntity<JSONObject> responseEntity =
        restTemplate.postForEntity(dataSourceUrl, requestBody, JSONObject.class);

    JSONObject responseBody = responseEntity.getBody();
    if (responseBody == null) {
      throw new ServiceException(RespStatus.INVALID_RESPONSE_FROM_OPC, this.getClass().getName());
    }
    return responseBody;
  }

  /*Task加入待处理队列*/
  public boolean addTaskToQueue(TaskInput task) {
    return processes.offer(task);
  }

  @Override
  public StateResponse queryECNState() {
    return null;
  }

  @Override
  public StateResponse queryTaskState(String processId, String taskId) {
    return null;
  }

  @Override
  public Map<Integer, List<Task>> retTasksPool() {
    return null;
  }
}
